const express = require('express');
const router = express.Router();
const db = require('../util/db')
const file = require('../util/file')
const errObj = require('../util/err');


const dbconfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  port: '3306',
  database: 'test'
}

/**
 * 连接数据库获取数据库表
 */
router.post('/connect', async (req, res) => {
  let cfj = dbconfig
  for (let key in req.body) {
    if (req.body[key]) {
      cfj[key] = req.body[key]
    }
  }
  global.database = cfj.database
  // 连接数据库
  db.connect(cfj)
  // 获取数据库表
  let sql = `SELECT table_name AS name,table_comment AS comment,create_time AS createTime FROM information_schema.tables WHERE table_schema='${cfj.database}'`
  let data = await db.query(sql)
  res.send(data)
});

/**
 * 获取数据库表详情
 */
router.post('/detail', async (req, res) => {
  let sql = `SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = '${global.database}' AND TABLE_NAME = '${req.body.name}';`
  let data = await db.query(sql)
  res.send(data)
});

/**
 * 获取数据库表详情
 */
router.post('/generate', async (req, res) => {
  try {
    global.tablePrefix = req.body.tablePrefix
    let data = await file.batchGenerator(req.body.tables)
    res.send({ ...errObj.success, ...{ aaData: data } })
  } catch (error) {
    res.send({
      "status": 80001,
      "msg": error.message
    })
  }
});

/**
 * 获取数据库表详情
 */
router.get('/download', async (req, res) => {
  let data = await file.downloadZip()
  res.download(data, 'generator.zip');
});

/**
 * 获取文件列表
 */
router.post('/getFiles', (req, res) => {
  try {
    let data = file.getFiles(req.body.folderName)
    res.send({ ...errObj.success, ...{ aaData: data } })
  } catch (error) {
    res.send({
      "status": 80001,
      "msg": error.message
    })
  }
});

/**
 * 编辑文件
 */
router.post('/updateFile', (req, res) => {
  try {
    file.updateFile(req.body)
    res.send(errObj.success)
  } catch (error) {
    res.send({
      "status": 80001,
      "msg": error.message
    })
  }
});

module.exports = router;
